package com.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.common.domain.entity.Comment;
import com.common.domain.entity.Consultation;
import com.common.domain.entity.ResponseResult;
import com.common.domain.vo.CommentVo;
import com.common.enums.AppHttpCodeEnum;
import com.common.mapper.CommentMapper;

import com.common.mapper.ConsultationMapper;
import com.common.service.CommentService;
import com.common.util.RedisCache;
import com.common.util.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author
 * @Date 2023/10/15 15:20
 **/
@Service
public class CommentServiceImpl  extends ServiceImpl<CommentMapper, Comment>
        implements CommentService {

    private final String COMMENT_DEF = "1";

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    ConsultationMapper consultationMapper;
    @Autowired
    private RedisCache redisCache;
    @Override
    public PageInfo<CommentVo> getCommentDetail(Long id, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        List<CommentVo> list = commentMapper.getDoctorCommentInfo(id);

        PageInfo<CommentVo> pageInfo = new PageInfo<>(list);

        pageInfo.setList(list);

        return pageInfo;
    }

    @Override
    public ResponseResult submitComment(Comment comment) {
        String userKey = SecurityUtils.getUserId() + "_comment";
        if(redisCache.exists(userKey)){
            return new ResponseResult().ok(AppHttpCodeEnum.OTHER_REQUESTS_ERROR);
        }
        try {
            Comment commentById = commentMapper.getCommentById(comment.getConsultationId());
            if(commentById != null){
                return new ResponseResult().errorResult(AppHttpCodeEnum.REPEAT_ERROR);
            }
            //保存评价
            save(comment);
            //修改状态
            Consultation consultation = new Consultation();
            consultation.setId(comment.getConsultationId());
            consultation.setCommentDef(COMMENT_DEF);
            consultationMapper.updateById(consultation);
            return ResponseResult.okResult();
        }catch (Exception e){
            //删除缓存
            return new ResponseResult().ok("评论失败，请稍后再试");
        }finally {
            //删除缓存
            redisCache.remove(userKey);
        }
    }

    @Override
    public ResponseResult getCommentById(Long id) {
       Comment comment =  commentMapper.getCommentById(id);
        return ResponseResult.okResult(comment);
    }


}
